/**
 * 一共N天，每天有M个糖果，每个糖果的价格Aij
 * 每天必须吃一个糖果，可以买k在[0, M]之间个糖果，且要额外付出k*k的代价
 * 问保证N天都有糖吃的最小代价
 * 令Dij是第i天保留j个糖果的最小代价，则
 * Dij = min{D[i-1][j+1-k] + k * k + 前k个糖果价格之和,k=0,1,2,...,M}
 */
#include <bits/stdc++.h>
using namespace std;

using llt = long long;
using pii = pair<int, int>;
using vi = vector<int>;

llt const INF = 0x1F2F3F4F5F6F7F8F;
llt const NINF = -INF;

int N, M;
vector<vector<llt>> A;
vector<vector<llt>> S;
vector<vector<llt>> D;

llt chkadd(llt a, llt b){
    if(-1 == a or -1 == b) return -1;
    return a + b;
}

void chkmin(llt & a, llt b){
    if(-1 == b) return;
    if(-1 == a or b < a) a = b;
    return;
}

void work(){
    cin >> N >> M;
    A.assign(N +  1, vector<llt>(M + 1, 0));
    S.assign(N +  1, vector<llt>(M + 1, 0));
    for(int i=1;i<=N;++i){
        for(int j=1;j<=M;++j) cin >> A[i][j];
        sort(A[i].begin() + 1, A[i].end());
        for(int j=1;j<=M;++j) S[i][j] = S[i][j - 1] + A[i][j];
    }

    D.assign(N + 1, vector<llt>(M + 1, -1));
    D[0][0] = 0;
    for(int i=1;i<=N;++i){
        auto & pre = D[i - 1];
        for(int j=0;j<=M;++j){
            auto & d = D[i][j];
            for(int k=max(0,j+1-M);k<=min(M,j+1);++k){
                auto tmp = chkadd(pre[j + 1 - k], k * k + S[i][k]);
                chkmin(d, tmp);
            }
        }
    }
    llt ans = -1;
    for(int i=0;i<=M;++i){
        chkmin(ans, D[N][i]);
    }
    cout << ans << endl;
    return;
}

int main(){
#ifndef ONLINE_JUDGE
    freopen("z.txt", "r", stdin);
#endif
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    int nofkase = 1;
    // cin >> nofkase; 
    while(nofkase--) work();
    return 0;
}
